import React, { useEffect, useImperativeHandle, useMemo, useRef, useState } from 'react';
// import { intl, nanoid10 } from "@/utils";
import { Button, CheckBox, Popup } from 'devextreme-react';
import { useModel } from 'umi';
import { DevGrid } from '~/public/cpas-ui';
import { LayoutD } from '~/public/cpas-ui/components-bs/Layout';
import './index.less';

import { msgInfo } from '@/utils/msg';
import { columnsDataBottom, columnsDataTop } from './columnData';
import { getPZBOneVoucherDetail, getPZBOneVoucherDetailOfAssist } from './service';
import { nanoid10 } from '@/utils';

const AccountingVoucherPupop = React.forwardRef((props: any, ref: any) => {
  const { initialState } = useModel('@@initialState');
  const { cellDblClickCallback } = props;

  const { zcbfName } = initialState?.curPart as any;
  const [visiblePopup, setVisiblePopup] = useState<boolean>(false);

  // const [eventsSaveData, setEventsSaveData] = useState<any[]>([]);
  const showDataRef = useRef<any>({});


  const rowDataRef = useRef<any>({});
  const [rowDataObj, setRowDataObj] = useState<any>({});
  const [rowDataShowObj, setRowDataShowObj] = useState<any>(null);
  const devGridRef = useRef<any>(null);
  const [oneVoucherDetail, setOneVoucherDetail] = useState<any[]>([]);
  const [oneVoucherDetailAssist, setOneVoucherDetailAssist] = useState<any[]>([]);
  const [oneVoucherDetail0, setOneVoucherDetail0] = useState<any>({});

  const [btnArr, setBtnArr] = useState<any[]>([]);
  const [btnArrIndex, setBtnArrIndex] = useState<number>(0);

  const [checkBoxFzz, setCheckBoxFzz] = useState<boolean>(true);
  const [checkBoxFzzAll, setCheckBoxFzzAll] = useState<boolean>(true);
  const [visibleTopKey, setVisibleTopKey] = useState<any>('top');
  const [visibleBottomKey, setVisibleBottomKey] = useState<any>('bottom');

  const onCancel = () => {
    setVisiblePopup(false);
    setOneVoucherDetailAssist([]);
    setOneVoucherDetail([]);
    setOneVoucherDetail0({});
    setBtnArrIndex(0);
    setBtnArr([]);
    //取消回调
    if (showDataRef.current?.cancelCallback) {
      showDataRef.current?.cancelCallback();
    }
  };

  const getPZBOneVoucherDetaiList = async (tempRowData: any) => {
    const res = await getPZBOneVoucherDetail({
      dbname: tempRowData.dbname,
      Data_ID: tempRowData.Data_ID,
      PZRQ: tempRowData.PZRQ,
      PZLX: tempRowData.PZLX,
      PZBH: tempRowData.PZBH,
    });
    if (res.success) {
      setOneVoucherDetail(
        res.data.map((item: any, inx: number) => {
          let index = inx
          item.rowIndex = ++index
          return item
        }));
      setVisibleTopKey(nanoid10());
      setOneVoucherDetail0(res.data[0]);
      rowDataRef.current = { ...tempRowData, FLID: res.data[0]?.FLID };
      setRowDataObj({ ...tempRowData, FLID: res.data[0]?.FLID });
    } else {
      setVisibleTopKey(nanoid10());
      setOneVoucherDetail([]);
      setOneVoucherDetail0({});
    }
  };

  const getPZBOneVoucherDetailOfAssistList = async (tempRowData: any) => {
    const res = await getPZBOneVoucherDetailOfAssist({
      dbname: tempRowData.dbname,
      Data_ID: tempRowData.Data_ID,
      PZRQ: tempRowData.PZRQ,
      PZLX: tempRowData.PZLX,
      PZBH: tempRowData.PZBH,
      FLID: tempRowData?.FLID ?? '',
    });
    if (res.success) {
      setVisibleBottomKey(nanoid10());
      setOneVoucherDetailAssist(res.data.map((item: any, inx: number) => {
        let index = inx
        item.rowIndex = ++index;
        item.itemGuid = nanoid10();
        return item
      }));
    } else {
      setVisibleBottomKey(nanoid10());
      setOneVoucherDetailAssist([]);
    }
  };

  // 自定义方法
  useImperativeHandle(ref, () => ({
    showPupop: (rowData: any, gapArr: any[]) => {
      setVisiblePopup(true);
      console.log(rowData, gapArr, '@@@');
      setBtnArrIndex(0);
      setCheckBoxFzz(true);
      setCheckBoxFzzAll(true);
      showDataRef.current = rowData;
      setRowDataShowObj(rowData);
      setBtnArr(gapArr);
    },
  }));

  useEffect(() => {
    if (rowDataShowObj?.PZBH) {
      setCheckBoxFzzAll(true);
      getPZBOneVoucherDetaiList(rowDataShowObj);
      getPZBOneVoucherDetailOfAssistList({ ...rowDataShowObj, FLID: '' });
    }
  }, [rowDataShowObj]);
  useEffect(() => {
    if (!checkBoxFzzAll) {
      getPZBOneVoucherDetailOfAssistList(rowDataRef.current);
    }
  }, [checkBoxFzzAll, rowDataObj]);

  function topContainer() {

    return <div style={{ height: 'calc(100% - 10px)' }}>
      {useMemo(() => {
        return (<DevGrid.RangeTap
          className={` PaperDevSortableGrid devHeadersCenter `}
          height={'100%'}
          width="100%"
          key={visibleTopKey}
          ref={devGridRef}
          dataSource={oneVoucherDetail}
          keyExpr="FLID"
          defaultColumns={columnsDataTop}
          excelName={`${zcbfName}(${rowDataShowObj?.PZRQ ?? ''}_${rowDataShowObj?.PZLX}_${rowDataShowObj?.PZBH ?? ''})`}
          showBorders={true}
          showRowLines={true}
          showColumnLines={true}
          allowColumnResizing={true}
          focusedRowEnabled={true}
          onCellClick={(e) => {
            const { rowType, data } = e;
            if (rowType === 'data') {
              rowDataRef.current = { ...rowDataRef.current, FLID: data.FLID };
              setRowDataObj({ ...rowDataRef.current, FLID: data.FLID });
            }
          }}
          onCellDblClick={(e) => {
            const { rowType, data, column } = e;
            if (rowType === 'data') {
              cellDblClickCallback(data, rowDataShowObj.Data_ID);
            }
          }}
          searchPanel={{
            visible: false,
            width: 180,
            placeholder: '',
          }}
          paging={{
            enabled: false,
          }}
          loadPanel={{ enabled: false }}
          scrolling={{
            mode: 'virtual',
            rowRenderingMode: 'virtual',
            renderAsync: true,
          }}
          sheetName={`123123`}
        // excelName={`123123`}
        />
        );
      }, [oneVoucherDetail, visibleTopKey, columnsDataTop, zcbfName, rowDataShowObj])}
    </div>



  }

  function bottomContainer() {
    return (
      <div
        style={{ height: 'calc(100% - 35px)', marginBottom: '10px' }}
        className="bottomContainBox"
      >

        {
          useMemo(() => {
            if (checkBoxFzz || checkBoxFzzAll) {
              return (<DevGrid.RangeTap
                className={` PaperDevSortableGrid devHeadersCenter `}
                height={'100%'}
                width="100%"
                key={visibleBottomKey}
                ref={devGridRef}
                dataSource={oneVoucherDetailAssist}
                keyExpr="itemGuid"
                defaultColumns={columnsDataBottom}
                excelName={`${zcbfName}(${rowDataShowObj?.PZRQ ?? ''}_${rowDataShowObj?.PZLX}_${rowDataShowObj?.PZBH ?? ''
                  })`}
                showBorders={true}
                showRowLines={true}
                showColumnLines={true}
                allowColumnResizing={true}
                searchPanel={{
                  visible: false,
                  width: 180,
                  placeholder: '',
                }}
                paging={{
                  enabled: false,
                }}
                loadPanel={{ enabled: false }}
                scrolling={{
                  mode: 'virtual',
                  rowRenderingMode: 'virtual',
                  renderAsync: true,
                }}
                sheetName={`123123`}
              // excelName={`123123`}
              />);
            }
            return <></>
          }, [oneVoucherDetailAssist, visibleBottomKey, columnsDataBottom, zcbfName, rowDataShowObj, checkBoxFzz, checkBoxFzzAll])
        }


        <div className="titleBox">
          <div className="leftTitle">
            <div className="leftTitleBox">
              <div className="leftTitleBoxText">编制人：</div>
              <div className="leftTitleBoxBorder textColor">{oneVoucherDetail0?.TZR ?? ''}</div>
            </div>
            <div className="leftTitleBox">
              <div className="leftTitleBoxText">审核人：</div>
              <div className="leftTitleBoxBorder textColor">{oneVoucherDetail0?.SHR ?? ''}</div>
            </div>
            <div className="leftTitleBox">
              <div className="leftTitleBoxText">记账人：</div>
              <div className="leftTitleBoxBorder textColor">{oneVoucherDetail0?.JZR ?? ''}</div>
            </div>
            <div className="leftTitleBox">
              <div className="leftTitleBoxText">附件张数：</div>
              <div className="leftTitleBoxBorder textColor">{oneVoucherDetail0?.PZZS ?? 0}</div>
            </div>
          </div>
        </div>
      </div>
    );
  }

  return (
    <Popup
      visible={visiblePopup}
      title="记账凭证"
      width={'80vw'}
      height={'70vh'}
      onHiding={() => {
        onCancel();
      }}
    >
      <div style={{ height: '100%', width: '100%' }}>
        <div
          style={{
            height: 'calc(100% - 40px)',
            width: '100%',
            overflow: 'hidden',
            border: '1px solid #000',
          }}
        >
          <div className="jzpzTitleBox">
            <div className="headerTitleCenter">
              <div className="headerTitleCenterText textColor">
                记账凭证
                <div className="headerTitleCenterborder"></div>
              </div>
            </div>
            <div className="titleBox">
              <div className="leftTitle">
                <div className="leftTitleBox">
                  <div className="leftTitleBoxText">凭证日期：</div>
                  <div className="leftTitleBoxBorder textColor">{rowDataShowObj?.PZRQ ?? ''}</div>
                </div>
                <div className="leftTitleBox">
                  <div className="leftTitleBoxText">凭证类型：</div>
                  <div className="leftTitleBoxBorder textColor">{rowDataShowObj?.PZLX ?? ''}</div>
                </div>
                <div className="leftTitleBox">
                  <div className="leftTitleBoxText">凭证编号：</div>
                  <div className="leftTitleBoxBorder textColor">{rowDataShowObj?.PZBH ?? ''}</div>
                </div>
              </div>

              <div className="rightBoxBtn">
                <Button
                  width={80}
                  text="上一张"
                  type="default"
                  stylingMode="text"
                  disabled={btnArrIndex === 0}
                  onClick={() => {
                    setBtnArrIndex((oldItem) => {
                      let newData = oldItem;
                      newData = newData - 1;
                      setRowDataShowObj(btnArr[newData]);
                      return newData;
                    });
                  }}
                />
                <Button
                  width={80}
                  text="下一张"
                  type="default"
                  stylingMode="text"
                  disabled={btnArrIndex === (btnArr.length - 1 <= 0 ? 0 : btnArr.length - 1)}
                  onClick={() => {
                    setBtnArrIndex((oldItem) => {
                      let newData = oldItem;
                      newData = newData + 1;
                      setRowDataShowObj(btnArr[newData]);
                      return newData;
                    });
                  }}
                />
              </div>
            </div>
          </div>
          <div style={{ width: '100%', height: 'calc(100% - 80px)' }}>
            <LayoutD
              // columnSize="100%"
              columnSize={['65%', '35%']}
              topSlot={topContainer()}
              bottomSlot={bottomContainer()}
            />
          </div>
        </div>

        <div
          style={{
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'left',
            marginTop: '8px',
          }}
        >
          <CheckBox
            text="显示辅助账信息"
            value={checkBoxFzz}
            onValueChanged={(e: any) => {
              console.log(e.value, '@@@ e.value');
              setCheckBoxFzz(e.value);
            }}
            style={{ marginRight: '15px' }}
          />
          <CheckBox
            text="显示全部辅助账信息"
            value={checkBoxFzzAll}
            onValueChanged={(e: any) => {
              setCheckBoxFzzAll(e.value);
              if (e.value) {
                getPZBOneVoucherDetailOfAssistList({ ...rowDataRef.current, FLID: '' });
              }
            }}
          />
        </div>
      </div>
    </Popup>
  );
});

export default AccountingVoucherPupop;
